from cgi import escape
from os.path import dirname, join, exists, basename
from collections import defaultdict
from shutil import move
from glob import glob

PREFIX = dirname(__file__)
PREFIX_OUTPUT = join(PREFIX, "plim")
PATH = join(PREFIX, "../pure", "world")

DEPTH_POS = defaultdict(int)


from mako.template import Template



def summary_iter():
    with open(join(PATH, "SUMMARY.md")) as summary:
        summary = list(summary)
        for i in summary:
            depth = int((len(i) - len(i.lstrip())) / 4)
            name, filename = i.lstrip(" *").split("](")
            name = name[1:]
            filename = filename.rstrip()[:-1]
            yield depth, name, filename


def rename():
    id = 10000
    for i in glob(join(PATH, "*.md")):
        i = (basename(i.strip())[:-3])
        if i.isdigit():
            i = int(i)
            if i > id:
                id = int(i)

    result = []
    for depth, name, filename in summary_iter():
        if not filename[:-3].isdigit():
            fpath = join(PATH, filename)
            id += 1
            print(name, id)
            filename = "%s.md" % id
            move(fpath, join(PATH, filename))
        result.append(
            "%s* [%s](%s)" % (
                "    " * depth,
                name,
                filename
            )
        )

    with open(join(PATH, "SUMMARY.md"), "w") as f:
        f.write("\n".join(result))

def link_file_iter():
    for depth, name, filename in summary_iter():
        with open(join(PATH, filename)) as f:
            txt = f.read()
            yield name, int(filename[:-3]), txt, depth

class LinkPrevNext:

    def __init__(self):
        self._result = result = [0]
        for name,id,txt,depth in link_file_iter():
            if not name.startswith("."):
                if txt.strip():
                    result.append(id)
        result.append(0)

    def __call__(self, id):
        r = self._result
        pos = r.index(id)
        return r[pos - 1], r[pos + 1]

rename()
link_prev_next = LinkPrevNext()

def render(id, txt):
    prev_link, next_link = link_prev_next(id)
    result = []
    result.append("""-inherit file="_base.plim"
-block head
    link rel="canonical" href="http://tz.world/book-%s"

-block title
    %s
    
-block book 
    - markdown
""" % (
        id,
        txt.strip(" \r\n").split("\n")[0].strip().lstrip("#"))
    )
    for i in txt.split("\n"):
        result.append(
            "        " + i.rstrip().replace("(image/", "(/world/image/"))
    result.append("""
-block nav 
    a.icon-menu.iconfont href="/#book%s"
    .pn
""" % id)
    if prev_link:
        result.append("""       a.prev href="/book-%s" &lt;\n""" % prev_link)
    if next_link:
        result.append("""       a.next href="/book-%s" &gt;""" % next_link)
    result = "\n".join(result)
    path = join(PREFIX_OUTPUT, "book", str(id) + ".plim")
    if exists(path):
        with open(path) as infile:
            if infile.read() == result:
                return

    with open(path, "w") as output:
        output.write(result)


def plim_render():
    result = []


    def depth_append(id, txt, depth, name):
        for k in list(DEPTH_POS.keys()):
            if k > depth:
                del DEPTH_POS[k]
        tab = "    "
        begin_tab = depth * 2 * tab
        pos = DEPTH_POS[depth] = (DEPTH_POS[depth] + 1)
        if pos == 1:
            result.append("""%s.l%s""" % (begin_tab, depth))
        link = "javascript:void(0)"
        if name.startswith("."):
            name = name[1:]
            p = "p.disable"
        elif not txt.strip():
            p = "p.disable"
        else:
            p = "p"
            link = "/book-%s" % id
        result.append("%s%s" % (begin_tab + tab, p))
        result.append("%s%s ." % (begin_tab + tab * 2, str(pos).zfill(2)))

        result.append("""%sa id="book%s" href="%s" %s""" % (
            begin_tab + tab * 2, id, link, name
        ))
    for name, id,txt,depth in link_file_iter():
        if not name.startswith("."):
            if txt.strip():
                render(id, txt)
        if name == "引子":
            result.append("""h2
    a href="/book-%s" %s""" % (id, name))
            result.append("ol")
            continue

        if depth == 0:
            DEPTH_POS = defaultdict(int)
            if name.startswith("."):
                name = name[1:]
                txt = ""
            if txt:
                html = """    li
        h2
            a href="/book-%s" %s""" % (id, name)
            else:
                html = """    li
        h2 %s""" % (name)
            result.append(html)
        else:
            depth_append(id, txt, depth, name)

    with open(join(PREFIX_OUTPUT, "_book.plim"), "w") as book:
        book.write("\n".join(result))

plim_render()
